function Figure4

Nfactors = 3;
addpath('basic_functions')
addpath('../Data')

[Return,Z,IsF,Nt,Chars,CharsNames] = package_data_all_greeks;
Return = Return.ret_daily;
[N,T,L] = size(Z);
CharsNames{47,1} = 'EW Market';

% construct W and X matrices that will be used for IPCA
W = NaN(L,L,T);
X = NaN(L,T);
for t = 1:T-1
    W(:,:,t) = squeeze(Z(IsF(:,t+1),t,:))'*squeeze(Z(IsF(:,t+1),t,:)) / Nt(t+1);
    X(:,t+1) = squeeze(Z(IsF(:,t+1),t,:))'*Return(IsF(:,t+1),t+1) / Nt(t+1);
    Return(~IsF(:,t+1),t+1) = NaN;
end
clear t

% zero alpha
[G, F] = IPCA(X,W,Nt,Nfactors);
r2 = IPCA_R2(G,F,Return,Z,IsF,X,W);

%% Construct contribution of portfolios to factors
% construct theta*ZZ
% first compute average Char for managed portfolios
CC = Chars; CC(:,:,47) = ones(N,T);
CC(isnan(CC)) = 0;
ZZ = NaN(L,L,T);
for t = 1:T-1
    WW = squeeze(Z(IsF(:,t+1),t,:))/Nt(t+1);
    ZZ(:,:,t+1) = WW'*squeeze(CC(IsF(:,t+1),t,:));
end
% then compute average chars for factors
F_chars = NaN(T,L,Nfactors);
for t = 1:T-1
    tt = G*(inv(G'*squeeze(W(:,:,t))*G));
    for i = 1:L
        F_chars(t+1,i,:) = tt(i,:)*ZZ(i,t+1);
    end
end
fchars = squeeze(nanmean(F_chars));

% construct theta*X
F_contribution = NaN(T,L,Nfactors);
thetat = NaN(T,L,Nfactors);
for t = 1:T-1
    tt = G*(inv(G'*squeeze(W(:,:,t))*G));
    thetat(t,:,:) = tt;
    for i = 1:L
        F_contribution(t+1,i,:) = tt(i,:)*X(i,t+1);
    end
end

% disp('********************************************')
f_contribution = 100*(squeeze(nanmean(F_contribution)));
NN = CharsNames;

figure(1)
set(gcf,'Position',[1 1 750 1500])
subplot(3,1,1)
GG = f_contribution(:,1);
[X,ia] = sortrows(GG,-1);
bar((1:size(GG,1)),GG(ia,1))
set(gca,'xtick',(1:size(GG,1)),'xticklabel',NN(ia),'XTickLabelRotation',270) %,'ylim',[-0.5 1]
title('Factor # 1')

subplot(3,1,2)
GG = f_contribution(:,2);
[X,ia] = sortrows(GG,-1);
bar((1:size(GG,1)),GG(ia,1))
set(gca,'xtick',(1:size(GG,1)),'xticklabel',NN(ia),'XTickLabelRotation',270)
title('Factor # 2')

subplot(3,1,3)
GG = f_contribution(:,3);
[X,ia] = sortrows(GG,-1);
bar((1:size(GG,1)),GG(ia,1))
set(gca,'xtick',(1:size(GG,1)),'xticklabel',NN(ia),'XTickLabelRotation',270)
title('Factor # 3')

saveas(gcf,'figures_outputs/Figure4.eps','epsc')
saveas(gcf,'figures_outputs/Figure4.jpg','jpg')
